<template>
  <div class="production-order">
    <h2>生产订单管理</h2>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.orderNo"
        placeholder="订单号关键字"
        class="input-item"
      />
      <el-input
        v-model="searchForm.minTemp"
        placeholder="最低温度"
        class="input-item"
      />
      <el-input
        v-model="searchForm.maxTemp"
        placeholder="最高温度"
        class="input-item"
      />
      <el-select
        v-model="searchForm.batchNo"
        placeholder="所有批次"
        class="input-item"
      >
        <el-option label="所有批次" value="" />
        <el-option
          v-for="batch in batchOptions"
          :key="batch.value"
          :label="batch.label"
          :value="batch.value"
        />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-bar">
      <el-button type="success" @click="handleAdd">添加生产订单</el-button>
      <el-button type="primary" @click="handleImportExcel">导入Excel</el-button>
      <el-button type="warning" @click="handleClearData">数据清洗</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="productionOrderNo" label="生产单号" width="180" />
      <el-table-column prop="batchNo" label="炉料批次" width="150" />
      <el-table-column prop="meltingTemperature" label="熔炼温度" width="120" />
      <el-table-column prop="inoculantAmount" label="孕育剂量" width="120" />
      <el-table-column prop="pouringTemperature" label="浇注温度" width="120" />
      <el-table-column prop="qualificationRate" label="合格率" width="120">
        <template #default="scope">
          {{ scope.row.qualificationRate * 100 }}%
        </template>
      </el-table-column>
      <el-table-column prop="inTime" label="入库日期" width="120" />
      <el-table-column prop="productionTime" label="生产日期" width="120" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === '已完成' ? 'success' : 'warning'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="生产单号">
          <el-input v-model="form.productionOrderNo" :disabled="!!form.id" />
        </el-form-item>
        <el-form-item label="炉料批次">
          <el-input v-model="form.batchNo" />
        </el-form-item>
        <el-form-item label="熔炼温度">
          <el-input-number 
            v-model="form.meltingTemperature"
            :precision="2"
            :step="0.1"
          />
        </el-form-item>
        <el-form-item label="孕育剂量">
          <el-input-number
            v-model="form.inoculantAmount"
            :precision="2"
            :step="0.1"
          />
        </el-form-item>
        <el-form-item label="浇注温度">
          <el-input-number
            v-model="form.pouringTemperature"
            :precision="2"
            :step="0.1"
          />
        </el-form-item>
        <el-form-item label="合格率">
          <el-input-number
            v-model="form.qualificationRate"
            :precision="2"
            :step="0.01"
            :max="1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="入库日期">
          <el-date-picker
            v-model="form.inTime"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="生产日期">
          <el-date-picker
            v-model="form.productionTime"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        
        <!-- 订单明细 -->
        <el-form-item label="订单明细">
          <el-table :data="form.details" border>
            <el-table-column label="材料比例">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.materialRatio"
                  :precision="2"
                  :step="0.01"
                  :max="1"
                  :min="0"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="danger"
                  @click="removeDetail(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="addDetail">添加明细</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ProductionOrder',
  data() {
    return {
      // 搜索表单
      searchForm: {
        orderNo: '',
        minTemp: '',
        maxTemp: '',
        batchNo: ''
      },
      // 表格数据
      tableData: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 对话框
      dialogVisible: false,
      dialogTitle: '添加生产订单',
      // 表单数据
      form: {
        productionOrderNo: '',
        batchNo: '',
        meltingTemperature: 0,
        inoculantAmount: 0,
        pouringTemperature: 0,
        qualificationRate: 0,
        inTime: '',
        productionTime: '',
        details: []
      },
      // 批次选项
      batchOptions: []
    }
  },
  created() {
    this.fetchData()
    this.fetchBatchOptions()
  },
  methods: {
    // 获取数据
    async fetchData() {
      try {
        const response = await this.$http.get('/api/productionorders', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            ...this.searchForm
          }
        })
        if (response.data.code === 1) {
          const data = response.data.data
          this.tableData = data.records || []
          this.total = data.total || 0
          this.currentPage = data.current || 1
          this.pageSize = data.size || 10
        } else {
          this.$message.error(response.data.msg || '获取数据失败')
        }
      } catch (error) {
        this.$message.error('获取数据失败')
      }
    },
    // 获取批次选项
    async fetchBatchOptions() {
      try {
        const response = await this.$http.get('/api/productionorders/batchnumbers')
        if (response.data.code === 1) {
          const data = response.data.data || []
          this.batchOptions = data.map(item => ({
            label: item,
            value: item
          }))
        } else {
          this.$message.error(response.data.msg || '获取批次选项失败')
        }
      } catch (error) {
        this.$message.error('获取批次选项失败')
      }
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    // 重置
    handleReset() {
      this.searchForm = {
        orderNo: '',
        minTemp: '',
        maxTemp: '',
        batchNo: ''
      }
      this.handleSearch()
    },
    // 添加
    handleAdd() {
      this.dialogTitle = '添加生产订单'
      this.form = {
        productionOrderNo: '',
        batchNo: '',
        meltingTemperature: 0,
        inoculantAmount: 0,
        pouringTemperature: 0,
        qualificationRate: 0,
        inTime: '',
        productionTime: '',
        details: []
      }
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑生产订单'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 删除
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该生产订单?', '提示', {
          type: 'warning'
        })
        await this.$http.delete(`/api/productionorders/${row.id}`)
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    // 提交表单
    async handleSubmit() {
      try {
        if (this.form.id) {
          await this.$http.put(`/api/productionorders/${this.form.id}`, this.form)
        } else {
          await this.$http.post('/api/productionorders', this.form)
        }
        this.$message.success('保存成功')
        this.dialogVisible = false
        this.fetchData()
      } catch (error) {
        this.$message.error('保存失败')
      }
    },
    // 添加明细
    addDetail() {
      this.form.details.push({
        materialRatio: 0
      })
    },
    // 删除明细
    removeDetail(index) {
      this.form.details.splice(index, 1)
    },
    // 导入Excel
    handleImportExcel() {
      // TODO: 实现Excel导入功能
    },
    // 数据清洗
    handleClearData() {
      // TODO: 实现数据清洗功能
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.production-order {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.input-item {
  width: 200px;
}

.operation-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style> 